# -*- coding: utf-8 -*-
import json
import logging
from datetime import datetime, timedelta
from django.views.generic import TemplateView
from django.utils.decorators import method_decorator
from common.mch import db as mch_db
from common.sms import db as sms_db
from common.utils.decorator import response_wrapper
from common.utils.api import token_required
from common.utils.tz import (
    utc_to_local_str,
    ts_to_local_date_str
)

_LOGGER = logging.getLogger('hydra')


class SmsView(TemplateView):
    def get(self, req):
        query_dct = req.GET.dict()
        from admin.views import add_query_fliter
        add_query_fliter(req, query_dct)
        _LOGGER.info('SmsView get orders: %s, ', query_dct)
        if query_dct.get('sms_time'):
            d = json.loads(query_dct['sms_time'])
            start = None
            end = None
            if d.get('$gte'):
                start = datetime.strptime(d['$gte'], '%Y-%m-%d %H:%M:%S') + timedelta(hours=8)
            if d.get('$lt'):
                end = datetime.strptime(d['$lt'], '%Y-%m-%d %H:%M:%S') + timedelta(hours=8)
            if start and not end:
                query_dct['sms_time'] = '''{"$gte":"''' + start.strftime('%Y-%m-%d %H:%M:%S') + '''"}'''
            if not start and end:
                query_dct['sms_time'] = '''{"$lt":"''' + end.strftime('%Y-%m-%d %H:%M:%S') + '''"}'''
            if start and end:
                query_dct['sms_time'] = '''{"$gte":"''' + start.strftime('%Y-%m-%d %H:%M:%S') + '''","$lt":"''' \
                                  + end.strftime('%Y-%m-%d %H:%M:%S') + '''"}'''

        items, total_count = sms_db.list_sms(query_dct)
        mch_names = mch_db.get_mch_name_dict()
        resp_items = []
        for item in items:
            data = item.as_dict()
            data['mch_id'] = mch_names[data['mch_id']]
            data['order_id'] = str(data['order_id'])
            data['created_at'] = utc_to_local_str(data['created_at'])
            data['updated_at'] = utc_to_local_str(data['updated_at'])
            resp_items.append(data)
        income, spend = sms_db.get_sms_record_overview(query_dct)
        return {'list': resp_items, 'page': query_dct.get('$page', 1),
                'size': len(resp_items), 'total_count': total_count, 'income': income, 'spend': spend}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(SmsView, self).dispatch(*args, **kwargs)